package api

import (
	"gcrontab/common"
	"net"
	"net/http"
	"time"
)

//任务的HTTP接口
type ApiServer struct {
	httpServer *http.Server
}

//单例模式
var G_apiServer *ApiServer

//服务路由
func serverRoute(mux *http.ServeMux) {
	mux.HandleFunc("/job/save", handleJobSave)
	mux.HandleFunc("/job/delete", handleJobDelete)
	mux.HandleFunc("/job/list", handleGetJobList)
	mux.HandleFunc("/job/kill", handleKillJob)
	mux.HandleFunc("/job/log", handJobLog)
	mux.HandleFunc("/register/list", handleRegisterList)
}

//静态文件路由
func staticRoute(mux *http.ServeMux) {
	staticDir := http.Dir(common.G_conifg.WebRoot) // 返回值：./web， 类型：http.Dir
	staticHandler := http.FileServer(staticDir)  //todo 如何工作的
	mux.Handle("/", http.StripPrefix("/", staticHandler))
}

//初始化服务
func InitApiServer() (err error) {
	mux := http.NewServeMux()
	//服务路由
	serverRoute(mux)
	//静态文件路由
	staticRoute(mux)
	//tcp监听
	listener, err := net.Listen("tcp", common.G_conifg.ApiPort)
	if err != nil {
		return err
	}

	//创建一个http服务
	httpServer := &http.Server{
		ReadTimeout:  time.Duration(common.G_conifg.ApiReadTimeOut) * time.Millisecond,
		WriteTimeout: time.Duration(common.G_conifg.ApiWriteTimeOut) * time.Millisecond,
		Handler:      mux,
	}

	//赋值单例
	G_apiServer = &ApiServer{
		httpServer: httpServer,
	}

	//启动服务
	go func() {
		err = httpServer.Serve(listener)
		if err != nil {
			return
		}
	}()
	return
}
